package com.gogowan.agroenterprise.newview;

import static com.gogowan.agroenterprise.utils.SystemBroadCast.SCN_CUST_ACTION_SCODE;
import static com.gogowan.agroenterprise.utils.SystemBroadCast.SCN_CUST_EX_SCODE;

import java.util.ArrayList;
import java.util.List;

import com.gogowan.agroenterprise.R;
import com.gogowan.agroenterprise.barcode.Intents;
import com.gogowan.agroenterprise.base.BaseActivity;
import com.gogowan.agroenterprise.utils.INewAdapterClick;
import com.gogowan.agroenterprise.utils.SystemBroadCast;
import com.gogowan.agroenterprise.utils.Utils;
import com.gogowan.agroenterprise.widget.adapter.HwScanAdapter;

import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Debug;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import org.w3c.dom.Text;

public class HWDialogActivity extends BaseActivity implements android.view.View.OnClickListener {

	private HwScanAdapter hwScanAdapter;
	private ArrayList<String> datas = new ArrayList<>();
	private ArrayList<String> scandatas = new ArrayList<>();
	private ListView lv;
	private LinearLayout md;
	private String emptyCode;
	private String emptyCode1;
	private Button btnOk;
	private Button btnCancel;
	private String type = "";
	private TextView qsCode;
	private TextView jsCode;
	private String qscode = "";
	private String jscode = "";
	private TextView textView;
	private int codenumber;
	@TargetApi(Build.VERSION_CODES.HONEYCOMB)
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.hwlx_dialog);
		this.setFinishOnTouchOutside(false);
		type = getIntent().getStringExtra("type");
		codenumber=getIntent().getIntExtra("codenumber",-1);
		// 箱码、盒码（服务器返回的）
		emptyCode = getIntent().getStringExtra("emptyCode");

		if (emptyCode == null) {
			emptyCode = "";
		}
		// 箱码、盒码（扫码获取的）
		emptyCode1 = getIntent().getStringExtra("emptyCode1");
		if (emptyCode1 == null) {
			emptyCode1 = "";
		}
		emptyCode = Utils.getCodeStr(emptyCode);
		emptyCode1 = Utils.getCodeStr(emptyCode1);

		List<String> list = getIntent().getStringArrayListExtra("scans");
		if (list != null && list.size() > 0) {
			scandatas.addAll(list);
		}
		initView();
	}

	private void initView() {
		TextView tv_add = (TextView) findViewById(R.id.tv_add);
		tv_add.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View view) {
				if(Debug.isDebuggerConnected()){
					Intent intent = new Intent(SCN_CUST_ACTION_SCODE);
					Bundle bundle = new Bundle();
					bundle.putString(SCN_CUST_EX_SCODE, "MA.156.M0.100366.0d04020016.S0123310.M230329.L20230301.V260328"+((int)(Math.random()*1000)));
					intent.putExtras(bundle);
					sendBroadcast(intent);
					Intent intent2 = new Intent(SCN_CUST_ACTION_SCODE);
					Bundle bundle2 = new Bundle();
					bundle2.putString(SCN_CUST_EX_SCODE, "MA.156.M0.100366.0d04020016.S0123310.M230329.L20230301.V260328"+((int)(Math.random()*1000)));
					intent2.putExtras(bundle2);
					sendBroadcast(intent2);
				}
			}
		});
		btnOk = (Button) findViewById(R.id.btnok);
		btnCancel = (Button) findViewById(R.id.btncancel);
		btnOk.setOnClickListener(this);
		btnCancel.setOnClickListener(this);
		qsCode = (TextView) findViewById(R.id.qscode);
		jsCode = (TextView) findViewById(R.id.jscode);
		md = (LinearLayout) findViewById(R.id.md);
		lv = (ListView) findViewById(R.id.lv);
		textView=(TextView)findViewById(R.id.count_tv);
		hwScanAdapter = new HwScanAdapter(this, datas, new INewAdapterClick() {
			@Override
			public void onItemClick(View view, int position) {
				datas.remove(position);
				hwScanAdapter.notifyDataSetChanged();
			}
		});
		lv.setAdapter(hwScanAdapter);

		if ("lx".equals(type)) {
			lv.setVisibility(View.VISIBLE);
			md.setVisibility(View.GONE);
		} else {
			lv.setVisibility(View.GONE);
			md.setVisibility(View.VISIBLE);
		}
		initScanView(CodeString -> {
			if (CodeString!=null){
				xiaobangScan(CodeString);
			}else {
				showToast(getString(R.string.scan_timeout_warn), 0);
			}
		});
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btnok:
			if (datas.size() > 0) {
				if ("md".equals(type) && datas.size() < 2) {
					Toast.makeText(getApplicationContext(), "请将码段扫描完整", Toast.LENGTH_SHORT).show();
					return;
				}
				Intent intent = getIntent();
				intent.putStringArrayListExtra(Intents.Scan.RESULTLIST, datas);
				setResult(Activity.RESULT_OK, intent);
				finish();
			} else {
				finish();
			}
			break;
		case R.id.btncancel:
			if (datas.size() > 0) {
				new AlertDialog.Builder(this).setTitle("信息提示").setMessage("确认要退出扫码页面吗？退出后扫码记录将会丢失！")
						.setPositiveButton("确定", new OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog, int which) {
								finish();
							}
						}).setNegativeButton("取消", new OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog, int which) {

							}
						}).create().show();
			} else {
				finish();
			}
			break;
		}

	}

	@Override
	public void onResume() {
		isVisible = true;
		super.onResume();
		//registerReceiver(new String[] { getString(R.string.SCAN_ACTION) });
		registerIDataReceiver(new String[] { getString(R.string.SCAN_IDATA_ACTION) });
	}

	@Override
	protected void onPause() {
		isVisible = false;
		super.onPause();
	}
	private void xiaobangScan(String  resultStr){
		if ("lx".equals(type)) {
			if (TextUtils.isEmpty(resultStr)) {

			} else if (emptyCode.trim().equals(Utils.getCodeStr(resultStr.trim()))
					|| emptyCode1.trim().equals(Utils.getCodeStr(resultStr.trim()))) {
				Toast.makeText(getApplicationContext(), "码号重复", Toast.LENGTH_SHORT).show();
			} else {
				if (scandatas.contains(Utils.getCodeStr(resultStr.trim()))) {
					Toast.makeText(getApplicationContext(), "码号重复", Toast.LENGTH_SHORT).show();
					return;
				}
				if (!(Utils.getCodeStr(resultStr.trim()) + "").startsWith("MA.156.M0")) {
					Toast.makeText(getApplicationContext(), "不合格的二维码，请重试！", Toast.LENGTH_SHORT).show();
					return;
				}
				Toast.makeText(getApplicationContext(), resultStr.trim() + "", Toast.LENGTH_SHORT).show();
				// Wait a moment or else it will scan the same
				// barcode
				// continuously about 3 times
				if (codenumber>0&&datas.size()>=codenumber){
					showToast(" 超度单次扫码数量");
					return;
				}
				scandatas.add(0,Utils.getCodeStr(resultStr.trim()) + "");
				datas.add(0,Utils.getCodeStr(resultStr.trim()) + "");
				hwScanAdapter.notifyDataSetChanged();
				textView.setText(datas.size()+"条数据");
			}
		} else if ("md".equals(type)) {
			if (TextUtils.isEmpty(resultStr)) {

			} else if (emptyCode.trim().equals(Utils.getCodeStr(resultStr.trim()))
					|| emptyCode1.trim().equals(Utils.getCodeStr(resultStr.trim()))) {
				Toast.makeText(getApplicationContext(), "码号重复", Toast.LENGTH_SHORT).show();
			} else {
				if (scandatas.contains(Utils.getCodeStr(resultStr.trim()))) {
					Toast.makeText(getApplicationContext(), "码号重复", Toast.LENGTH_SHORT).show();
					return;
				}

				qscode = qsCode.getText().toString().trim();
				jscode = jsCode.getText().toString().trim();
				if (TextUtils.isEmpty(qscode)) {
					qsCode.setText(Utils.getCodeStr(resultStr.trim()));
					datas.add(0,Utils.getCodeStr(resultStr.trim()) + "");
					scandatas.add(0,Utils.getCodeStr(resultStr.trim()) + "");
				} else if (TextUtils.isEmpty(jscode)) {
					jsCode.setText(Utils.getCodeStr(resultStr.trim()));
					datas.add(0,Utils.getCodeStr(resultStr.trim()) + "");
					scandatas.add(0,Utils.getCodeStr(resultStr.trim()) + "");
				} else {
					Toast.makeText(getApplicationContext(), "已扫码完成，无需扫码", Toast.LENGTH_SHORT).show();
				}
			}
		}
	}
	@Override
	protected void handleReceiver(Context context, Intent intent) {
		super.handleReceiver(context, intent);
		if (isVisible) {
			if (getString(R.string.SCAN_ACTION).equals(intent.getAction())) {
				String scanStatus = intent.getStringExtra(getString(R.string.SCAN_STATE));
				if ("ok".equals(scanStatus)) {
					// 成功
					String resultStr = intent.getStringExtra(getString(R.string.DATA_STRING)).trim();
					// 生成单元

					if ("lx".equals(type)) {
						if (TextUtils.isEmpty(resultStr)) {

						} else if (emptyCode.trim().equals(Utils.getCodeStr(resultStr.trim()))
								|| emptyCode1.trim().equals(Utils.getCodeStr(resultStr.trim()))) {
							Toast.makeText(getApplicationContext(), "码号重复", Toast.LENGTH_SHORT).show();
						} else {
							if (scandatas.contains(Utils.getCodeStr(resultStr.trim()))) {
								Toast.makeText(getApplicationContext(), "码号重复", Toast.LENGTH_SHORT).show();
								return;
							}
							Toast.makeText(getApplicationContext(), resultStr.trim() + "", Toast.LENGTH_SHORT).show();
							// Wait a moment or else it will scan the same
							// barcode
							// continuously about 3 times
							scandatas.add(0,Utils.getCodeStr(resultStr.trim()) + "");
							datas.add(0,Utils.getCodeStr(resultStr.trim()) + "");
							hwScanAdapter.notifyDataSetChanged();
							textView.setText(datas.size()+"条数据");
						}
					} else if ("md".equals(type)) {
						if (TextUtils.isEmpty(resultStr)) {

						} else if (emptyCode.trim().equals(Utils.getCodeStr(resultStr.trim()))
								|| emptyCode1.trim().equals(Utils.getCodeStr(resultStr.trim()))) {
							Toast.makeText(getApplicationContext(), "码号重复", Toast.LENGTH_SHORT).show();
						} else {
							if (scandatas.contains(Utils.getCodeStr(resultStr.trim()))) {
								Toast.makeText(getApplicationContext(), "码号重复", Toast.LENGTH_SHORT).show();
								return;
							}

							qscode = qsCode.getText().toString().trim();
							jscode = jsCode.getText().toString().trim();
							if (TextUtils.isEmpty(qscode)) {
								qsCode.setText(Utils.getCodeStr(resultStr.trim()));
								datas.add(0,Utils.getCodeStr(resultStr.trim()) + "");
								scandatas.add(0,Utils.getCodeStr(resultStr.trim()) + "");
							} else if (TextUtils.isEmpty(jscode)) {
								jsCode.setText(Utils.getCodeStr(resultStr.trim()));
								datas.add(0,Utils.getCodeStr(resultStr.trim()) + "");
								scandatas.add(0,Utils.getCodeStr(resultStr.trim()) + "");
							} else {
								Toast.makeText(getApplicationContext(), "已扫码完成，无需扫码", Toast.LENGTH_SHORT).show();
							}
						}
					}
				} else {
					// 失败如超时等
					showToast(getString(R.string.scan_timeout_warn), 0);
				}
			}
		}
	}
	
	
	@Override
	protected void handleIDataReceiver(Context context, Intent intent) {
		// TODO Auto-generated method stub
		super.handleIDataReceiver(context, intent);
		if (isVisible) {
//			String scanResult1 = intent.getStringExtra("value");
			if (getString(R.string.SCAN_IDATA_ACTION).equals(intent.getAction())) {
				String scanResult = intent.getStringExtra("value")+"";
				if (scanResult.contains("s.idcode.org.cn")){
					return;
				}
				if (!Utils.isEmpty(scanResult)&&scanResult.length() > 0) {
					// 生成单元
					if ("lx".equals(type)) {
						if (TextUtils.isEmpty(scanResult)) {

						} else if (emptyCode.trim().equals(Utils.getCodeStr(scanResult.trim()))
								|| emptyCode1.trim().equals(Utils.getCodeStr(scanResult.trim()))) {
							Toast.makeText(getApplicationContext(), "码号重复", Toast.LENGTH_SHORT).show();
						} else {
							if (scandatas.contains(Utils.getCodeStr(scanResult.trim()))) {
								Toast.makeText(getApplicationContext(), "码号重复", Toast.LENGTH_SHORT).show();
								return;
							}
							Toast.makeText(getApplicationContext(), scanResult.trim() + "", Toast.LENGTH_SHORT).show();
							// Wait a moment or else it will scan the same
							// barcode
							// continuously about 3 times
							scandatas.add(0,Utils.getCodeStr(scanResult.trim()) + "");
							datas.add(0,Utils.getCodeStr(scanResult.trim()) + "");
							hwScanAdapter.notifyDataSetChanged();
							textView.setText(datas.size()+"条数据");
						}
					} else if ("md".equals(type)) {
						if (TextUtils.isEmpty(scanResult)) {

						} else if (emptyCode.trim().equals(Utils.getCodeStr(scanResult.trim()))
								|| emptyCode1.trim().equals(Utils.getCodeStr(scanResult.trim()))) {
							Toast.makeText(getApplicationContext(), "码号重复", Toast.LENGTH_SHORT).show();
						} else {
							if (scandatas.contains(Utils.getCodeStr(scanResult.trim()))) {
								Toast.makeText(getApplicationContext(), "码号重复", Toast.LENGTH_SHORT).show();
								return;
							}

							qscode = qsCode.getText().toString().trim();
							jscode = jsCode.getText().toString().trim();
							if (TextUtils.isEmpty(qscode)) {
								qsCode.setText(Utils.getCodeStr(scanResult.trim()));
								datas.add(0,Utils.getCodeStr(scanResult.trim()) + "");
								scandatas.add(0,Utils.getCodeStr(scanResult.trim()) + "");
							} else if (TextUtils.isEmpty(jscode)) {
								jsCode.setText(Utils.getCodeStr(scanResult.trim()));
								datas.add(0,Utils.getCodeStr(scanResult.trim()) + "");
								scandatas.add(0,Utils.getCodeStr(scanResult.trim()) + "");
							} else {
								Toast.makeText(getApplicationContext(), "已扫码完成，无需扫码", Toast.LENGTH_SHORT).show();
							}
						}
					}
				} else {
					// 失败如超时等
					showToast(getString(R.string.scan_timeout_warn), 0);
				}
			}
		}
	}
	

	@Override
	public void onBackPressed() {
		if (datas.size() > 0) {
			new AlertDialog.Builder(this).setTitle("信息提示").setMessage("确认要退出扫码页面吗？退出后扫码记录将会丢失！")
					.setPositiveButton("确定", new OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {
							finish();
						}
					}).setNegativeButton("取消", new OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {

						}
					}).create().show();
		} else {
			finish();
		}
	}

}
